import * as echarts from 'echarts';
import React, { useRef, useEffect, useCallback } from 'react';

import type { ECharts, EChartsOption, SetOptionOpts } from 'echarts';

// 组件属性接口
interface EChartsReactProps {
  option: EChartsOption; // ECharts配置项
  theme?: string | object; // 主题名称或配置对象
  style?: React.CSSProperties; // 容器样式
  className?: string; // 容器类名
  settings?: SetOptionOpts; // ECharts setOption的配置项
  loading?: boolean; // 是否显示加载动画
  loadingOption?: object; // 加载动画配置
  onChartReady?: (chart: ECharts) => void; // 图表初始化完成回调
  onEvents?: Record<string, Function>; // 事件处理函数
  autoResize?: boolean; // 是否自动调整大小
}

const EChartsReact: React.FC<EChartsReactProps> = ({ 
  option, 
  theme, 
  style, 
  className, 
  settings, 
  loading = false, 
  loadingOption, 
  onChartReady, 
  onEvents, 
  autoResize = true 
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<ECharts | null>(null);

  // 初始化图表
  const initChart = useCallback(() => {
    if (!chartRef.current) return;

    try {
      // 如果已存在实例，先销毁
      if (chartInstance.current) {
        chartInstance.current.dispose();
      }

      // 创建新实例
      chartInstance.current = echarts.init(chartRef.current, theme);

      // 设置初始配置
      chartInstance.current.setOption(option, settings);

      // 触发就绪回调
      if (onChartReady) {
        onChartReady(chartInstance.current);
      }

      // 绑定事件
      if (onEvents) {
        Object.keys(onEvents).forEach((eventName) => {
          if (typeof onEvents[eventName] === 'function') {
            chartInstance.current?.on(eventName, (params: any) => {
              onEvents[eventName](params, chartInstance.current);
            });
          }
        });
      }
    } catch (error) {
      console.error('ECharts初始化失败:', error);
    }
  }, [theme, option, settings, onChartReady, onEvents]);

  // 处理加载状态
  const handleLoading = useCallback(() => {
    if (!chartInstance.current) return;

    if (loading) {
      chartInstance.current.showLoading(loadingOption);
    } else {
      chartInstance.current.hideLoading();
    }
  }, [loading, loadingOption]);

  // 调整大小处理函数
  const resizeHandler = useCallback(() => {
    if (chartInstance.current && autoResize) {
      chartInstance.current.resize();
    }
  }, [autoResize]);

  // 初始化效果和依赖处理
  useEffect(() => {
    initChart();
    handleLoading();

    // 添加窗口调整大小监听
    let resizeObserver: ResizeObserver | null = null;
    
    if (autoResize && chartRef.current) {
      // 使用ResizeObserver替代window.resize事件以获得更好的性能
      if (typeof window !== 'undefined' && window.ResizeObserver) {
        resizeObserver = new ResizeObserver(resizeHandler);
        resizeObserver.observe(chartRef.current);
      } else {
        // 降级到window.resize事件
        window.addEventListener('resize', resizeHandler);
      }
    }

    // 清理函数
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
      
      // 清理resize监听器
      if (resizeObserver && chartRef.current) {
        resizeObserver.unobserve(chartRef.current);
      } else if (autoResize) {
        window.removeEventListener('resize', resizeHandler);
      }
    };
  }, [initChart, handleLoading, resizeHandler, autoResize]);

  // 选项更新处理
  useEffect(() => {
    if (chartInstance.current) {
      chartInstance.current.setOption(option, settings);
      handleLoading();
    }
  }, [option, settings, handleLoading]);

  // 主题变化处理
  useEffect(() => {
    if (chartInstance.current) {
      // 使用echarts的主题切换功能而不是重新初始化整个图表
      chartInstance.current.dispose();
      initChart();
    }
  }, [theme, initChart]);

  return <div ref={chartRef} style={{ height: '100%', width: '100%', ...style }} className={className} />;
};

export default EChartsReact;
